package com.bstek.urule.controller;

import com.bstek.urule.Configure;
import com.bstek.urule.model.flow.FlowDefinition;
import com.bstek.urule.runtime.KnowledgePackage;
import com.bstek.urule.runtime.KnowledgePackageWrapper;
import com.bstek.urule.runtime.cache.CacheUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 更新规则引擎知识包
 *
 * @author gehongbin
 * @since 2022/01/18
 */
@RestController
public class KnowledgePackageReceiverController {

    private static final Logger log = LogManager.getLogger(KnowledgePackageReceiverController.class);

    public static final String URL="/knowledgepackagereceiver";

    @ResponseBody
    @PostMapping("/knowledgepackagereceiver")
    public String knowledgePackageReceiver(@RequestBody KnowledgePackageReceiverDto knowledgePackageReceiverDto) throws IOException {

        String packageId=knowledgePackageReceiverDto.getPackageId();
        packageId= URLDecoder.decode(packageId, "utf-8");
        if(packageId.startsWith("/")){
            packageId=packageId.substring(1,packageId.length());
        }
        String content=knowledgePackageReceiverDto.getContent();
        content=URLDecoder.decode(content, "utf-8");
        ObjectMapper mapper=new ObjectMapper();
        mapper.getDeserializationConfig().withDateFormat(new SimpleDateFormat(Configure.getDateFormat()));
        KnowledgePackageWrapper wrapper=mapper.readValue(content, KnowledgePackageWrapper.class);
        wrapper.buildDeserialize();
        KnowledgePackage knowledgePackage=wrapper.getKnowledgePackage();
        Map<String, FlowDefinition> flowMap=knowledgePackage.getFlowMap();
        if(flowMap!=null && flowMap.size()>0){
            for(FlowDefinition fd:flowMap.values()){
                fd.buildConnectionToNode();
            }
        }
        CacheUtils.getKnowledgeCache().putKnowledge(packageId, knowledgePackage);
        return "ok";
    }
}
